package com.example.administrator.music;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.sms.listener.VerifySMSCodeListener;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by Administrator on 2018/3/30.
 */

public class WangjimimaActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView back;
    private EditText phone, yanzhengma, mima;
    private Button fasong, queding;
    private String id;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wanjimima);
        initview();
        Bmob.initialize(this, "6aeb83da9239b94d7c6773a50f22c5d3");
        BmobSMS.initialize(this, "6aeb83da9239b94d7c6773a50f22c5d3");

    }

    private void initview() {
        back = (ImageView) findViewById(R.id.wangjimima_back);
        phone = (EditText) findViewById(R.id.wangjimima_phone);
        yanzhengma = (EditText) findViewById(R.id.wangjimima_yzm);
        mima = (EditText) findViewById(R.id.wangjimima_chongzhimima);
        fasong = (Button) findViewById(R.id.wangjimima_fasong);
        queding = (Button) findViewById(R.id.wangjimima_chongzhi);
        queding.setEnabled(false);
        fasong.setEnabled(false);


        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String ph = String.valueOf(s);
                if (isPhoneNumber(ph)) {
                    fasong.setEnabled(true);
                    fasong.setBackgroundResource(R.drawable.button);
                } else {
                    fasong.setEnabled(false);
                    fasong.setBackgroundResource(R.drawable.huibutton);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        yanzhengma.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phg = String.valueOf(phone.getText());
                String yzm = String.valueOf(s);
                BmobSMS.verifySmsCode(WangjimimaActivity.this, phg, yzm, new VerifySMSCodeListener() {
                    @Override
                    public void done(cn.bmob.sms.exception.BmobException e) {
                        if (e == null) {
                            queding.setEnabled(true);
                            queding.setBackgroundResource(R.drawable.button);

                        } else {
                            queding.setEnabled(false);
                            queding.setBackgroundResource(R.drawable.huibutton);
                        }
                    }
                });
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        queding.setOnClickListener(this);
        fasong.setOnClickListener(this);
        back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wangjimima_back:
                finish();
                break;
            case R.id.wangjimima_fasong:
                Toast.makeText(WangjimimaActivity.this, "请稍候", Toast.LENGTH_SHORT).show();
                BmobQuery<MusicPlayUser> query = new BmobQuery<MusicPlayUser>();
                query.addWhereEqualTo("phongNo", String.valueOf(phone.getText()));
                query.findObjects(new FindListener<MusicPlayUser>() {
                    @Override
                    public void done(List<MusicPlayUser> list, BmobException e) {
                        if (e == null) {
                            if (list.size() == 0) {
                                Toast.makeText(WangjimimaActivity.this, "该号码还未注册，请前往注册", Toast.LENGTH_SHORT).show();
                            } else {
                                String phongNo = String.valueOf(phone.getText());
                                BmobSMS.requestSMSCode(WangjimimaActivity.this, phongNo, "Zzh短信验证服务", new RequestSMSCodeListener() {
                                    @Override
                                    public void done(Integer integer, cn.bmob.sms.exception.BmobException e) {
                                        if (e == null) {
                                            Toast.makeText(WangjimimaActivity.this, "验证码已发送，请注意查收", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }
                        }
                    }
                });

                break;
            case R.id.wangjimima_chongzhi:
                String nepassword = String.valueOf(mima.getText());
                if (nepassword.equals("")) {
                    Toast.makeText(WangjimimaActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(WangjimimaActivity.this, "正在查询，请稍候", Toast.LENGTH_SHORT).show();
                    BmobQuery<MusicPlayUser> bmobQuery = new BmobQuery<MusicPlayUser>();
                    bmobQuery.addWhereEqualTo("phongNo", String.valueOf(phone.getText()));
                    bmobQuery.findObjects(new FindListener<MusicPlayUser>() {
                        @Override
                        public void done(List<MusicPlayUser> list, BmobException e) {
                            if (e == null) {
                                if (list.size() != 0) {
                                    File file1 = new File("/data/data/com.example.administrator.music/files/musicusername");
                                    File file2 = new File("/data/data/com.example.administrator.music/files/musicuserobjectId");
                                    if (file1.exists()) {
                                        file1.delete();
                                    }
                                    if (file2.exists()) {
                                        file2.delete();
                                    }
                                    for (MusicPlayUser user : list) {
                                        id = user.getObjectId();
                                        String un = user.getUsername();
                                        saveMassage(id, "musicuserobjectId");
                                        saveMassage(un, "musicusername");
                                    }
                                } else {
                                    Toast.makeText(WangjimimaActivity.this, "设置失败", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(WangjimimaActivity.this, "发生错误：" + e, Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    Toast.makeText(WangjimimaActivity.this, "正在修改，请稍等", Toast.LENGTH_SHORT).show();
                    MusicPlayUser playUser = new MusicPlayUser();
                    playUser.setPassword(nepassword);
                    playUser.setMode(MainActivity.playmode);
                    playUser.setTheme(MainActivity.theme);
                    playUser.update(id, new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                Toast.makeText(WangjimimaActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        }
                    });
                }
                break;

        }
    }

    //判断字符串为电话号码的格式
    public static boolean isPhoneNumber(String phoneNo) {
        if (TextUtils.isEmpty(phoneNo)) {
            return false;
        }
        if (phoneNo.length() == 11) {
            for (int i = 0; i < 11; i++) {
                if (!PhoneNumberUtils.isISODigit(phoneNo.charAt(i))) {
                    return false;
                }
            }
            Pattern p = Pattern.compile("^((13[^4,\\D])" + "|(134[^9,\\D])" +
                    "|(14[5,7])" +
                    "|(15[^4,\\D])" +
                    "|(17[3,6-8])" +
                    "|(18[0-9]))\\d{8}$");
            Matcher m = p.matcher(phoneNo);
            return m.matches();
        }
        return false;
    }

    public void saveMassage(String inputText, String textname) {//inputText为传入的要保存的数据
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            //textname为文件名，第二个参数为文件操作模式：文件已经存在，就往文件里面追加类容，不从新创建文件。
            out = openFileOutput(textname, Context.MODE_APPEND);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //读取文件，返回String类型
    public String load(String data) {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput(data);           //“data”为文件名
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                line = line + "\n";               //换行
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }


}
